package com.x.mvp.crypto;

import android.util.Log;

import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    private static String AESPARAM = "AES/CBC/PKCS7Padding";

    private SecretKeySpec keyspec;
    private AlgorithmParameterSpec ivsaps = getIV();

    private Cipher getCipher() {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(AESPARAM);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "getCipher():", e);
        }
        return cipher;
    }

    private AlgorithmParameterSpec getIV() {
        byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        IvParameterSpec ivParameterSpec;
        ivParameterSpec = new IvParameterSpec(iv);

        return ivParameterSpec;
    }

    public byte[] encrypt(byte[] data) throws Exception {
        Cipher cipher = getCipher();
        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivsaps);
        byte[] encrypted = cipher.doFinal(data);
        return encrypted;
    }

    public byte[] decrypt(byte[] data) throws Exception {
        Cipher cipher = getCipher();
        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivsaps);
        byte[] decrypted = cipher.doFinal(data);
        return decrypted;
    }

    public void setKey(byte[] key) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(key);
        byte[] keyBytes = new byte[32];
        System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
        keyspec = new SecretKeySpec(keyBytes, "AES");
    }
}
